package com.lwl.concurrency.executor;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class UseAllResultTest {

	static class Result {
		private String name;
		private long value;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public long getValue() {
			return value;
		}

		public void setValue(long value) {
			this.value = value;
		}

	}

	static class Task implements Callable<Result> {
		private String name;

		public Task(String name) {
			this.name = name;
		}

		@Override
		public Result call() throws Exception {
			System.out.println(name+" start..."+LocalDateTime.now());
			Random random = new Random();
			TimeUnit.SECONDS.sleep(random.nextInt(10));
			
			Result result = new Result();
			result.setName(this.name);
			result.setValue(Thread.currentThread().getId());
			System.out.println(name+" end..."+LocalDateTime.now());
			
			return result;
		}

	}
	
	public static void main(String[] args) throws ExecutionException {
		ExecutorService executorService = Executors.newCachedThreadPool();
		List<Task> taskList = new ArrayList<>();
		for (int i = 0; i < 3; i++) {
			Task task = new Task("Task-"+i);
			taskList.add(task);
		}
		try {
			System.out.println("调用开始"+LocalDateTime.now());
			List<Future<Result>> results = executorService.invokeAll(taskList);
			executorService.shutdown();
			System.out.println("调用结束"+LocalDateTime.now());
			int size = results.size();
			for (int i = 0; i <size;  i++) {
				Future<Result> future = results.get(i);
				Result result = future.get();
				System.out.println(result.getName()+" "+result.getValue());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
		
	}

}
